package com.kkang.netpan.service;


import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher;
import org.apache.hive.jdbc.HiveQueryResultSet;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class HiveJDBC {
    private static String driverName = "org.apache.hive.jdbc.HiveDriver";
    private static String url = "jdbc:hive2://192.168.17.90:10000/mydb";
    private static String user = "hadoop";
    private static String password = "";

    private static Connection conn = null;
    private static Statement stmt = null;
    private static ResultSet rs = null;

    public  HiveJDBC () throws Exception {
        Class.forName(driverName);
        conn = DriverManager.getConnection(url,user,password);
        stmt = conn.createStatement();
    }

 /*   public String getTables() throws Exception {
        ResultSet set = null ;
        try {
             set = stmt.executeQuery("select url from midresult limit 2");
             set.next();
             return set.getString(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "error";
    }*/

    public List<Map<String , Object>> executor (String sql) {
        ResultSet set = null ;
        try {
            set = stmt.executeQuery(sql);
            return resultProcession(set) ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null ;
    }

    public List<Map<String , Object>> resultProcession(ResultSet set)  {
        List<Map<String , Object>> resultset = new LinkedList<>();
        try {
            ResultSetMetaData metaData = set.getMetaData();
            int columnCount = metaData.getColumnCount();
            //构造结果集
            while (set.next()) {
                resultset.add(new HashMap<String , Object>());
                for (int i = 1 ; i <= columnCount ; i++) {
                    resultset.get(resultset.size()-1).put(metaData.getColumnLabel(i) , set.getString(i));
                }

            }
            return resultset;
        } catch (SQLException e){
            System.out.println("error");
        }
        return  null ;
    }


    public void destory() throws Exception {
        if ( rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }



}
